import 'dart:math';

import 'package:dali_ng_pera/manager/dnp_cache_manager.dart';
import 'package:flutter/material.dart';

import '../widget/dnp_app_bar.dart';

class DnpCreditPage extends StatefulWidget {
  const DnpCreditPage({super.key});

  @override
  State<DnpCreditPage> createState() => _DnpCreditPageState();
}

class _DnpCreditPageState extends State<DnpCreditPage> {
  String? _creditScore;

  String get key{
    return DnpCacheManager().getString("ho_phone") ?? "";
  }

  String get curCredit{
    return DnpCacheManager().getString(key) ?? "0";
  }

  String getRandomCredit(){
    String randomCreditValue = DnpCacheManager().getString(key) ?? "";
    if(randomCreditValue.isNotEmpty){
      return randomCreditValue;
    }
    // 生成 85 到 99 之间的随机数
    final random = Random();
    int credit = 85 + random.nextInt(15); // 15 = 99 - 85
    DnpCacheManager().saveString(key, credit.toString());
    return credit.toString();
  }

  void _evaluateCredit() {
    setState(() {
      _creditScore = getRandomCredit();
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Container(
        decoration: BoxDecoration(
          gradient: LinearGradient(
            begin: Alignment.topCenter,
            end: Alignment.bottomCenter,
            colors: [
              Color(0xFF53A9FF),
              Color(0xFFDFF1FF),
            ],
          ),
        ),
        child: Column(
          children: [
            DnpAppBar(title: "Credit assessment"),
            Expanded(
              child: SingleChildScrollView(
                child: Column(
                  children: [
                    Container(
                      padding: EdgeInsets.symmetric(horizontal: 16, vertical: 24),
                      child: Column(
                        mainAxisAlignment: MainAxisAlignment.center,
                        children: [
                          // 圆形信用分数显示
                          Container(
                            width: 197,
                            height: 197,
                            decoration: BoxDecoration(
                              shape: BoxShape.circle,
                              color: Colors.white,
                              boxShadow: [
                                BoxShadow(
                                  color: Colors.black.withOpacity(0.1),
                                  blurRadius: 20,
                                  spreadRadius: 5,
                                ),
                              ],
                            ),
                            child: Stack(
                              alignment: Alignment.center,
                              children: [
                                // 外圈蓝色边框
                                Container(
                                  width: 159,
                                  height: 159,
                                  child: ArcProgressWidget(
                                    value: double.parse(_creditScore ?? curCredit),
                                    size: 159,
                                    strokeWidth: 4,
                                    backgroundColor: Color(0xFFB1D9FF),
                                    progressColor: Color(0xFF0193FE),
                                  ),
                                ),
                                Container(
                                  width: 121,
                                  height: 121,
                                  decoration: BoxDecoration(
                                    shape: BoxShape.circle,
                                    color: Color(0xFFDFF1FF),
                                  ),
                                ),
                                // 分数文字
                                Text(
                                  _creditScore ?? curCredit,
                                  style: TextStyle(
                                    fontSize: 71,
                                    fontWeight: FontWeight.w600,
                                    color: Color(0xFF1D4AC8),
                                  ),
                                ),
                              ],
                            ),
                          ),
                          SizedBox(height: 24),
                          Text(
                            "Credit score",
                            style: TextStyle(
                              fontSize: 20,
                              fontWeight: FontWeight.w600,
                              color: Colors.white,
                            ),
                          ),
                          SizedBox(height: 8),
                          _descWidget()
                        ],
                      ),
                    ),
                    GestureDetector(
                      onTap: _evaluateCredit,
                      child: Container(
                        width: double.infinity,
                        height: 48,
                        alignment: Alignment.center,
                        margin: EdgeInsets.only(left: 16,right: 16,bottom: 18),
                        decoration: BoxDecoration(
                            color: Color(0xFF1D4AC8),
                            borderRadius: BorderRadius.circular(16)
                        ),
                        child: Text("To evaluate",style: TextStyle(
                          color: Colors.white,
                          fontSize: 16,
                          fontWeight: FontWeight.w600,
                        ),),
                      ),
                    ),
                    Container(
                      margin: EdgeInsets.only(left: 16,right: 16,bottom: 34),
                      child: Image.asset(
                        "assets/images/ic_credit_bottom_bg.webp",
                        width: double.infinity,
                        height: 354,
                        fit: BoxFit.fill,
                      ),
                    )
                  ],
                ),
              ),
            )
          ],
        ),
      ),
    );
  }

  Widget _descWidget() {
    if (curCredit != "0") {
      return RichText(
        text: TextSpan(
          text: "More than ",
          style: TextStyle(
            fontSize: 14,
            color: Colors.white,
          ),
          children: [
            TextSpan(
              text: "94.2%",
              style: TextStyle(
                fontSize: 14,
                color: Color(0xFFF59E0B),
                fontWeight: FontWeight.w600,
              ),
            ),
            TextSpan(
              text: " of the users nationwide",
              style: TextStyle(
                fontSize: 14,
                color: Colors.white,
              ),
            ),
          ],
        ),
      );
    }else {
      return Text(
        'You currently dont\'t have a credit report',
        style: TextStyle(
          fontSize: 16,
          color: Color(0xFFDDEEFF),
        ),
      );
    }
  }
}

class ArcProgressWidget extends StatelessWidget {
  final double value; // 0-100 的值
  final double size;
  final double strokeWidth;
  final Color backgroundColor;
  final Color progressColor;

  const ArcProgressWidget({
    Key? key,
    required this.value,
    this.size = 200,
    this.strokeWidth = 4,
    this.backgroundColor = Colors.grey,
    this.progressColor = Colors.blue,
  }) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return CustomPaint(
      size: Size(size, size),
      painter: ArcProgressPainter(
        value: value,
        strokeWidth: strokeWidth,
        backgroundColor: backgroundColor,
        progressColor: progressColor,
      ),
    );
  }
}

class ArcProgressPainter extends CustomPainter {
  final double value;
  final double strokeWidth;
  final Color backgroundColor;
  final Color progressColor;

  ArcProgressPainter({
    required this.value,
    required this.strokeWidth,
    required this.backgroundColor,
    required this.progressColor,
  });

  @override
  void paint(Canvas canvas, Size size) {
    final center = Offset(size.width / 2, size.height / 2);
    final radius = (size.width - strokeWidth) / 2;

    // 绘制背景圆弧
    final backgroundPaint = Paint()
      ..color = backgroundColor
      ..strokeWidth = strokeWidth
      ..style = PaintingStyle.stroke
      ..strokeCap = StrokeCap.round;

    // 绘制进度圆弧
    final progressPaint = Paint()
      ..color = progressColor
      ..strokeWidth = strokeWidth
      ..style = PaintingStyle.stroke
      ..strokeCap = StrokeCap.round;

    // 绘制背景圆环（完整的圆）
    canvas.drawCircle(center, radius, backgroundPaint);

    // 绘制进度圆弧
    final sweepAngle = 2 * pi * (value / 100);
    final rect = Rect.fromCircle(center: center, radius: radius);

    canvas.drawArc(
      rect,
      -pi / 2, // 从顶部开始（-90度）
      sweepAngle,
      false,
      progressPaint,
    );

    // 可选：添加文字显示百分比
    _drawText(canvas, center, value);
  }

  void _drawText(Canvas canvas, Offset center, double value) {
    final textPainter = TextPainter(
      text: TextSpan(
        text: '${value.toInt()}%',
        style: TextStyle(
          fontSize: 24,
          fontWeight: FontWeight.bold,
          color: Colors.black,
        ),
      ),
      textAlign: TextAlign.center,
      textDirection: TextDirection.ltr,
    );

    textPainter.layout();
    final textOffset = Offset(
      center.dx - textPainter.width / 2,
      center.dy - textPainter.height / 2,
    );
    textPainter.paint(canvas, textOffset);
  }

  @override
  bool shouldRepaint(covariant CustomPainter oldDelegate) {
    return true;
  }
}